<?php
/**
 *   Kaltura Browser - components/com_kaltura/models/kalturaentries.php
 *   Author: Juan Dapena Paz (juan@bittingbits.com)
 *   Copyright (C) 2011 Bitting Bits S.L.
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');
class KalturaModelKalturaentries extends JModel
{
    var $_data;
    var $_page;
    var $_total;
    var $_edb; // external database connection
    var $_instance;
    var $_step = 10;
    
    function __construct() {
        parent::__construct();
        global $mainframe, $option;
        
        $limit = $mainframe->getUserStateFromRequest('global.list.limit','limit',$mainframe->getCfg('list_limit'), 'int');
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
    }
    
    function getInstanceMetadata() {
        $query = 'select * from #__Kaltura_instances where id='.$this->_id;
        $this->_db->setQuery($query);
        $this->_instance = $this->_db->loadObject();
        return $this->_instance;
    }
    
    function setId($id) {
        $this->_id = $id;
        $this->_page = 1;
        $this->_data = null;
        $this->_instance = $this->getInstanceMetadata();
        
        $this->_edb =& ExternalDatabase::getDatabaseInstance($this->_id);
    }
    
    function setItemId($itemid) {
        $this->_item_id = $itemid;
        $this->_object = null;
    }
    
    function getItem() {
        if (empty($this->_object)) {
            $query = 'select * from entry where id="'.$this->_item_id.'"';
            $this->_edb->setQuery($query);
            $this->_object = $this->_edb->loadObject();
        }
        return $this->_object;
    }
    
    function getFieldsList() {
        $query = 'select * from #__Kaltura_fields where field_visible=1';
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }
    
    function getFieldValue($field_id) {
        $query = 'select * from #__Kaltura_entry_field_value';
        $query .= ' where kentry_id="'.$this->_item_id.'" and field_id='.$field_id;
        
        $this->_db->setQuery($query);
        return $this->_db->loadObject();
    }
    
    function _buildQuery() {
        $query = 'SELECT id, name, type, plays, description, ';
        $query .= 'date_format(created_at, "%d/%m/%y %H:%i") as created_at, ';
        $query .= 'length_in_msecs, status, flavor_params_ids, categories FROM entry ';
        $query .= 'WHERE type <> 5 and status = 2 and (partner_id = '.($this->_instance->userid).')';
        return $query;
    }
    
    function _buildFilter() {
        $query = "";
        
        // load created between
        $init_date = JRequest::getVar('init_date');
        $end_date = JRequest::getVar('end_date');
        if ($init_date) {
            $query .= ' and (created_at > str_to_date('.$init_date.'))';
        } else if ($init_date && $end_date) {
            $query .= ' and ((created_at > str_to_date('.$init_date.')) or ';
            $query .= '(created_at < str_to_date('.$end_date.')))';
        }
    
        // load search field data
        $searchfield = JRequest::getVar('q');
        if ($searchfield) {
            $query .= ' and name like "%'.$searchfield.'%"';
        }
        
        // load media type filter
        $mediafilters = JRequest::getVar('mediafilters');
        if ($mediafilters) {
            $query .= ' and (';
            $query .= 'media_type in ('.$mediafilters.')';
            $query .= ')';
        }
        
        // load duration filter
        $durationfilters = JRequest::getVar('durationfilters');
        if ($durationfilters) {
            $durationfilters = explode(',', $durationfilters);
            $query .= ' and (';
            foreach ($durationfilters as $k => $filter) {
                if ($filter == 1) {
                    $query .= ' (length_in_msecs < '.(4*60*1000).')';
                } else if ($filter == 2) {
                    $query .= ' ((length_in_msecs > '.(4*60*1000).') and';
                    $query .= ' (length_in_msecs < '.(20*60*1000).'))';
                } else if ($filter == 3) {
                    $query .= ' (length_in_msecs > '.(20*60*1000).')';
                }
                if ($k < (count($durationfilters)-1)) $query .= ' or';
            }
            $query .= ')';
        }
        
        // load statuses filter
        $statusesfilters = JRequest::getVar('statusesfilters');

        if ($statusesfilters) {
            $query .= ' and (';
            $query .= 'moderation_status in ('.$statusesfilters.')';
            $query .= ')';
        }
        
        // category filter
        $category_label = JRequest::getVar('cat');
        if ($category_label && ($category_label != 'categoriesall')) {  
            $query .= ' and (';
            $query .= 'find_in_set("'.$category_label.'", categories_ids) > 0';
            $query .= ')';
        }
        
        return $query;
    }
    
    function setPage($page) {
        $this->_page = $page;
        $this->_data = null;
    }
    
    function getTotal() {
        if (empty($this->_total)) {
		    $query = $this->_buildQuery();
		    $query .= $this->_buildFilter();
		    $this->_edb->setQuery($query);
		    $this->_edb->query();
		    $this->_total = $this->_edb->getNumRows();
		}
		return $this->_total;
    }
    
    function getMaxPages($step=10) {
        $this->_step = $step;
        $total = $this->getTotal();
        $pages = floor($total / $step)+1;
        return $pages;
    }
    
    function getData() {
        if (empty($this->_data)) {
            $query = $this->_buildQuery();
            $query .= $this->_buildFilter();
            $query .= ' order by name ';
            if ($this->_step)
                $query .= ' limit '.((JRequest::getVar('page')-1)*10).', '.$this->_step;
            
            $this->_edb->setQuery($query);

            $this->_data = $this->_edb->loadObjectList();
            
        }
        return $this->_data;
    }
    
    function getFlavors() {
        $query = 'select flavor_params_ids from entry where id="'.$this->_item_id.'"';
        $this->_edb->setQuery($query);
        $flavors = $this->_edb->loadResult();
        $flavors_ids = explode(",", $flavors);
        
        $query = 'select name from flavor_params where id in (';
        foreach ($flavors_ids as $k => $id) { 
            $query .= $id.(($k < (count($flavors_ids)-1))?',':'');
        }
        $query .= ')';
        
        $this->_edb->setQuery($query);
        return $this->_edb->loadResultArray();
    }
    
    function getCategories(&$root=null, $parent=null) {
        $query = 'select * from category';
        
        if ($parent) $query .= ' where parent_id='.$parent->id;
        else $query .= ' where parent_id=0';
        
        $query .= ' and partner_id='.$this->_instance->userid;
        $query .= ' and deleted_at is null';
        
        $this->_edb->setQuery($query);
        $cat_bulk = $this->_edb->loadObjectList();
        
        foreach ($cat_bulk as &$cat) {
            if ($parent) $cat->parent = $parent->id;
            else $cat->parent = 0;
            $cat->children = array();
            $this->getCategories($cat->children, $cat);
        }
        
        if (!$parent) return $cat_bulk;
        else $root = $cat_bulk;
    }
    
    function getCustomFilters() {
        $query = 'select * from ';
    }
    
    function getInstances() {
        $query = 'select * from #__Kaltura_instances';
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }
    
}
?>
